/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbenglish_client.form;

import bllInterface.*;
import bllfactory.SBLLFactory;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Highlighter;
import model.ClientFriendListModel;
import model.ClientModel;
import model.chat.ChatMessageModel;
import model.rooms.FriendListenerImpl;

/**
 *
 * @author Mrkupi
 */
public class roomChat extends javax.swing.JFrame implements ListDataListener {

    private boolean isBoss = false;
    private boolean isOn = false;
    
    private String roomID;
    private String roomName;
    
    private ChatMessageModel msgModel;
    private ClientFriendListModel model;
    private DefaultListModel newModel = new DefaultListModel();
    private ArrayList<String> strModel = new ArrayList();
    private iFriendListener friendListener;
    //======================
    TargetDataLine targetDataLine;
    PipedInputStream input;
    IRemoteBufferedOutputStream output;
    AudioFormat audioFormat;
    SourceDataLine sourceDataLine;
    byte tempBuffer[] = new byte[10000];
    int current = 0;
    
    Thread capture;
    Thread play;
    //======================

    /**
     * Creates new form roomChat
     */
    public roomChat(ChatMessageModel msgModel, String roomID, String roomName, boolean isBoss) throws RemoteException {
        initComponents();

        this.roomName   =   roomName;
        
        if (isBoss) {
            btnPostQuestion.setText("Talk");
            this.isBoss = true;
            msgModel.setIsBoss(isBoss);
        } else {
            btnPostQuestion.setText("Listen");
        }

        // HARD CODED
        setLocation(400, 200);
        this.roomID = roomID;

        msgModel.addListDataListener(this);
        this.lblNickName.setText(ClientModel.getInstance().getAccount().getUserName());
        this.lblRoomName.setText(this.roomName);
        this.msgModel   =   msgModel;

        // Model load room member
        this.model = new ClientFriendListModel();
        model.addListDataListener(this);

        initWindowCustomize();
        loadRoomMember();
        loadUserInfo();
        
        // Load history
        loadRoomHistory();
    }

    @Override
    public void dispose(){
        try {
            if(play != null)
                play.stop();
            if(capture != null)
                capture.stop();
            
            SBLLFactory.getInstance().getChat().getRoom(roomID).leave(ClientModel.getInstance().getChatUser());
            System.out.println("Leave Success");

            bllfactory.SBLLFactory.getInstance().getChat().getRoom(roomID).removeFriendListener(friendListener);
            
            if(RoomContainer.Container.containsKey( roomID ))
                RoomContainer.Container.remove( roomID );
        } catch (RemoteException ex) {
            System.out.println("Leave Fail");
            Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
        }
        super.dispose();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblRoomName = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taChatbox = new javax.swing.JTextArea();
        tfChat = new javax.swing.JTextField();
        btEnter = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        pnAvatar = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        lblLevel = new javax.swing.JLabel();
        lblExp = new javax.swing.JLabel();
        lblNickName = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        btnPostQuestion = new javax.swing.JButton();
        btnAttachFile = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblRoomName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblRoomName.setText("ROOM NAME");

        taChatbox.setEditable(false);
        taChatbox.setColumns(20);
        taChatbox.setLineWrap(true);
        taChatbox.setRows(5);
        taChatbox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                taChatboxMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(taChatbox);

        tfChat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                onEnter_pressed(evt);
            }
        });

        btEnter.setText("Enter");
        btEnter.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onEnter_clicked(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Level");

        jLabel3.setText("Exp");

        jLabel4.setText("Nick name");

        pnAvatar.setBorder(new javax.swing.border.MatteBorder(null));

        jButton1.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\HEINS_DESKTOP_LOOKUPS BRUCE.png")); // NOI18N

        javax.swing.GroupLayout pnAvatarLayout = new javax.swing.GroupLayout(pnAvatar);
        pnAvatar.setLayout(pnAvatarLayout);
        pnAvatarLayout.setHorizontalGroup(
            pnAvatarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pnAvatarLayout.setVerticalGroup(
            pnAvatarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        lblLevel.setText("jLabel5");

        lblExp.setText("jLabel6");

        lblNickName.setText("jLabel7");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblLevel)
                            .addComponent(lblExp)
                            .addComponent(lblNickName)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(pnAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(pnAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lblLevel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblExp))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblNickName))
                .addContainerGap())
        );

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("ROOMATES");
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnPostQuestion.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\kaboodle.png")); // NOI18N
        btnPostQuestion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPostQuestionActionPerformed(evt);
            }
        });

        btnAttachFile.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\Doawnload.png")); // NOI18N
        btnAttachFile.setText("Attach File");
        btnAttachFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAttachFileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnPostQuestion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAttachFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tfChat)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btEnter, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(322, 322, 322)
                .addComponent(lblRoomName)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(lblRoomName)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(4, 4, 4)
                                .addComponent(btnPostQuestion)
                                .addGap(5, 5, 5)
                                .addComponent(btnAttachFile)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(tfChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btEnter)))
                    .addComponent(jLabel1))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void onEnter_pressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_onEnter_pressed
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {                                
            sendMessageToAllRoomates( tfChat.getText() );
            tfChat.setText("");
        }
    }//GEN-LAST:event_onEnter_pressed

    private void onEnter_clicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onEnter_clicked
        sendMessageToAllRoomates( tfChat.getText() );
        tfChat.setText("");
    }//GEN-LAST:event_onEnter_clicked

//=============================================================
    private void btnPostQuestionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPostQuestionActionPerformed
        if ( isBoss ) 
        {
            Capture();
        } else 
        {
            Listen();
        }
    }//GEN-LAST:event_btnPostQuestionActionPerformed

    private void btnAttachFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAttachFileActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.showOpenDialog(this);
        
        File fileChosen = fileChooser.getSelectedFile();
        if( fileChosen != null )
        {
            try {
                FileInputStream fis = new FileInputStream(fileChosen);
                byte[] contents = new byte[(int)fileChosen.length()];
                fis.read(contents);

                // Create file message
                FileMessage fm = null;
                fm = FileMessage.createMessage(ClientModel.getInstance().getAccount().getUserID(), 
                                                fileChosen.getName(), contents, roomID);
                SBLLFactory.getInstance().getServerChat().postFile( fileChosen.getName(), fm );

                fis.close();

            } catch (FileNotFoundException | RemoteException ex) {
                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_btnAttachFileActionPerformed

    private void taChatboxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_taChatboxMouseClicked
        
        int currentPos = taChatbox.getCaretPosition();
        int counter = 0;
        for (String line : taChatbox.getText().split("\\n")) 
        {
            counter += line.length() + 1;
            if(counter >= currentPos && line.contains(" - Download "))
            {
                String fileName = line.replace(" - Download ", "");
                String[] arr = fileName.split(": ");
                try {
                    downloadFile(arr[1]);
                } catch (RemoteException ex) {
                    Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_taChatboxMouseClicked

    private void downloadFile( String fileName ) throws RemoteException, IOException{
        FileMessage fm = SBLLFactory.getInstance().getServerChat().getFile(fileName);
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.showSaveDialog(this);

        String pathName = fileChooser.getSelectedFile().getAbsolutePath();
        CharSequence arr = fileName.subSequence(fileName.length() - 4, fileName.length());
        fileName = pathName + arr;
        
        FileOutputStream fos = new FileOutputStream(fileName);
        fos.write(fm.getContent());
        fos.close();
        
        JOptionPane.showMessageDialog(this, fileName + "Completed");
    }
    
    private void Capture(){
        if( btnPostQuestion.getText().equals("Talk") && capture == null )
        {
            btnPostQuestion.setText("Silent");
            try {
                Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
                System.out.println("Available mixers:");
                for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
                    System.out.println(mixerInfo[cnt].getName());
                }

                audioFormat = getAudioFormat();
                DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
                sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
                sourceDataLine.open(audioFormat);
                sourceDataLine.start();
                captureAudio();
            }
            catch ( LineUnavailableException ex ) {
                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else 
        {
            btnPostQuestion.setText("Talk");
            if( capture != null )
            {
                capture.stop();
                capture = null;
            }
        }
    }
    
    private void Listen(){
        if( btnPostQuestion.getText().equals("Listen") )
        {
            btnPostQuestion.setText( "Stop" );
            try {
            if( play != null )
                return;

            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
            System.out.println("Available mixers:");
            for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
                System.out.println(mixerInfo[cnt].getName());
            }
            audioFormat = getAudioFormat();

            DataLine.Info dataLineInfo1 = new DataLine.Info(
                    SourceDataLine.class, audioFormat);
            sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo1);
            sourceDataLine.open(audioFormat);
            sourceDataLine.start();

            play = new PlayThread();
            play.start();
            } catch (LineUnavailableException ex) {
                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else 
        {
            btnPostQuestion.setText( "Listen" );
            if( play != null )
            {
                play.stop();
                play = null;
            }
        }
    }
    
    private void captureAudio() {
        try {
            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
            System.out.println("Available mixers:");
            for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
                System.out.println(mixerInfo[cnt].getName());
            }
            audioFormat = getAudioFormat();

            DataLine.Info dataLineInfo = new DataLine.Info(
                    TargetDataLine.class, audioFormat);

            Mixer mixer = AudioSystem.getMixer(mixerInfo[3]);

            targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo);

            targetDataLine.open(audioFormat);
            targetDataLine.start();

            capture = new CaptureThread();
            capture.start();
        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        }
    }

    class CaptureThread extends Thread {

        byte tempBuffer[] = new byte[7000];

        @Override
        public void run() {
            while (true) {
                int cnt = targetDataLine.read(tempBuffer, 0, tempBuffer.length);
                try {
                    SBLLFactory.getInstance().getServerChat().postVoice(ClientModel.getInstance().getAccount().getUserID(), roomID, tempBuffer);
                } catch (RemoteException ex) {
                    Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    class PlayThread extends Thread {

        @Override
        public void run() {
            if(!isBoss)
            {
                while ( true )
                {
                    byte[] src = msgModel.getBytes();
                    if( !isBoss && src != null )
                    {
                        sourceDataLine.write(src, 0, src.length);
                    }
                }
            }
        }
    }

    private AudioFormat getAudioFormat() {
        float sampleRate = 8000.0F;
        int sampleSizeInBits = 16;
        int channels = 1;
        boolean signed = true;
        boolean bigEndian = false;
        return new AudioFormat(
                sampleRate,
                sampleSizeInBits,
                channels,
                signed,
                bigEndian);
    }
//=============================================================

    private boolean sendMessageToAllRoomates( String message ) {
        // NEED TABLE
        if (!makeSureNotEmptyTextField()) {
            return false;
        }
        try {
            // put code send message
            ChatMessage cm = ChatMessage.createMessage(ClientModel.getInstance().getAccount().getUserID(), message, this.roomID);
            SBLLFactory.getInstance().getServerChat().post(cm);
        } catch (RemoteException ex) {
            Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Connection error!!");
        }

        return true;
    }

    private boolean makeSureNotEmptyTextField() {
        // NEED TABLE
        if ("".equals(tfChat.getText())) {
            JOptionPane.showMessageDialog(this, "Empty message");
            return false;
        }

        return true;
    }

    private void publishNewMessageToTextArea(ChatMessage message) {
        
        int pos = taChatbox.getText().length();
        this.taChatbox.append("\n" + String.format("%s: %s", message.getContent().get(ChatMessageContent.ORIGINAL_SENDER), message.getContent().get(ChatMessageContent.MESSAGE_CONTENT)));
        if( message.isFile() )
        {
            this.taChatbox.append( " - Download " );
            Highlighter h = taChatbox.getHighlighter();
            String text = String.format("%s: %s", message.getContent().get(ChatMessageContent.ORIGINAL_SENDER), message.getContent().get(ChatMessageContent.MESSAGE_CONTENT));           
            try {
                h.addHighlight(pos, taChatbox.getText().length() - 1, new UnderlineHighlighter.UnderlineHighlightPainter(Color.BLUE));
            } catch (BadLocationException ex) {
                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btEnter;
    private javax.swing.JButton btnAttachFile;
    private javax.swing.JButton btnPostQuestion;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblExp;
    private javax.swing.JLabel lblLevel;
    private javax.swing.JLabel lblNickName;
    private javax.swing.JLabel lblRoomName;
    private javax.swing.JPanel pnAvatar;
    private javax.swing.JTextArea taChatbox;
    private javax.swing.JTextField tfChat;
    // End of variables declaration//GEN-END:variables
    // Extends attribute
    private javax.swing.JList roomMembers;
    private javax.swing.JScrollPane scrollPaneFriendlist;

    @Override
    public void intervalAdded(ListDataEvent e) {
        if (e.getSource() instanceof ChatMessageModel) {
            ChatMessageModel chatMsgModel = (ChatMessageModel) e.getSource();
            try {
                for (int i = e.getIndex0(); i < e.getIndex1(); ++i) {
                    ChatMessage cm = (ChatMessage) chatMsgModel.getElementAt(i);
                    if (cm.getSender() == null ? ClientModel.getInstance().getAccount().getUserID() != null : !cm.getSender().equals(ClientModel.getInstance().getAccount().getUserID())) {
                        this.publishNewMessageToTextArea(cm);
                    }
                }
            } catch (RemoteException ex) {
                Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else if (e.getSource() instanceof Boolean){
            if( play != null )
            {
                play.stop();
                play = null;
                
                btnPostQuestion.setText( "Talk" );
                this.isBoss = true;
            }
        }
        else if (e.getSource() instanceof ClientFriendListModel) {
            model = (ClientFriendListModel) e.getSource();
            for (int i = e.getIndex0(); i < e.getIndex1(); ++i) {
                Account cm = (Account) model.getElementAt(i);
                try {
                    newModel.addElement(cm.getUserName());
                    roomMembers.setModel(newModel);

                    strModel.add("Level: " + cm.getLevel() + ", Exp: " + cm.getExp());
                } catch (RemoteException ex) {
                    Logger.getLogger(menu.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    @Override
    public void intervalRemoved(ListDataEvent e) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void contentsChanged(ListDataEvent e) {
    }

    protected void initWindowCustomize() {
        setResizable(false);
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });

        taChatbox.setWrapStyleWord(true);
        DefaultCaret dc = (DefaultCaret) taChatbox.getCaret();
        dc.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        scrollPaneFriendlist = new javax.swing.JScrollPane();
        roomMembers = new javax.swing.JList(model) {
            @Override
            public String getToolTipText(MouseEvent e) {
                int index = locationToIndex(e.getPoint());
                if (-1 < index) {
                    return strModel.get(index);
                } else {
                    return null;
                }
            }
        };

        scrollPaneFriendlist.setViewportView(roomMembers);
        roomMembers.setLocation(555, 80);
        roomMembers.setVisible(true);
        roomMembers.setSize(150, 320);
        roomMembers.setBorder(BorderFactory.createLineBorder(Color.black));
        roomMembers.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    Object selected =   roomMembers.getSelectedValue();
                    String strRoom  =   (String) selected;
                    Account acc = model.getAcc(strRoom);
                    if( acc != null )
                    {
                        try {
                            createPrivateChat( acc.getUserID(), acc.getUserName() );
                        } catch (RemoteException ex) {
                            Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        });
        roomMembers.addMouseListener(dc);
        this.add(roomMembers);
    }

    public void createPrivateChat( String id, String name ){
        if( !RoomContainer.Container.containsKey(id) )
        {
            ChatMessageModel chatMsgModel = new ChatMessageModel();
            ClientModel.getInstance().getChatMsgModels().put(id, chatMsgModel);
            privateChat pc = new privateChat(chatMsgModel, id, name);
            pc.setVisible(true);
            RoomContainer.Container.put(id, pc);
        }
    }
    
    protected void loadRoomHistory() {
        try {
            ArrayList<ChatMessage> messages = bllfactory.SBLLFactory.getInstance().getChat().getRoom(roomID).getHistory();
            for (ChatMessage cm : messages) {
                this.taChatbox.append("\n" + String.format("%s: %s", cm.getSender(), cm.getContent().get(ChatMessageContent.MESSAGE_CONTENT)));
            }
        } catch (RemoteException ex) {
            System.out.println("Error load history");
        }
    }

    protected void loadUserInfo() {
        try {
            this.lblNickName.setText(new String(ClientModel.getInstance().getAccount().getUserName().getBytes(), "UTF-8"));

            this.lblExp.setText(String.valueOf(ClientModel.getInstance().getAccount().getExp()));
            this.lblLevel.setText(String.valueOf(ClientModel.getInstance().getAccount().getLevel()));
        } catch (RemoteException | UnsupportedEncodingException ex) {
            Logger.getLogger(userInfo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    protected void loadRoomMember() {
        try {
            this.friendListener = new FriendListenerImpl();
            ((FriendListenerImpl) this.friendListener).addListListener(this);
            bllfactory.SBLLFactory.getInstance().getChat().getRoom(roomID).addFriendListener(friendListener);
        } catch (RemoteException ex) {
            Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
